package edu.mtu.citizenscience.ethnography;

import java.io.IOException;
import java.text.DateFormat;

import edu.mtu.citizenscience.ethnography.database.Interview;
import edu.mtu.citizenscience.ethnography.database.InterviewFileStatus;
import edu.mtu.citizenscience.ethnography.uploader.EthnographyUploadService;
import edu.mtu.citizenscience.ethnography.util.DataServiceActivity;
import edu.mtu.citizenscience.ethnography.util.LoginDialogFragment;
import edu.mtu.citizenscience.ethnography.util.UploadDialogFragment;
import edu.mtu.citizenscience.ethnography.util.Util;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class InterviewDetailActivity extends DataServiceActivity {

	private static final String LOG_TAG = "InterviewDetailActivity";

	public static final String ID_KEY = "interviewID";

	private TextView storyTitleView;
	private TextView subjectNameView;
	private TextView interviewerNameView;
	private TextView locationView;
	private TextView dateView;

	private TextView errorTextView;

	private Button listRecordingsButton;
	private Button viewPhotosButton;
	private Button uploadButton;

	private int interviewID;
	private Interview interview;

	private LoginBroadcastReceiver receiver;
	private LocalBroadcastManager manager;
	private IntentFilter intentFilter = new IntentFilter(EthnographyUploadService.UPLOAD_SERVICE);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_interview_detail);

		storyTitleView = (TextView) findViewById(R.id.storyTitleLabel);
		subjectNameView = (TextView) findViewById(R.id.subjectNameField);
		interviewerNameView = (TextView) findViewById(R.id.interviewerNameField);
		locationView = (TextView) findViewById(R.id.locationNameField);
		dateView = (TextView) findViewById(R.id.dateField);

		errorTextView = (TextView) findViewById(R.id.filesystemErrorField);

		listRecordingsButton = (Button) findViewById(R.id.list_audio_button);
		viewPhotosButton = (Button) findViewById(R.id.view_photos_button);
		uploadButton = (Button) findViewById(R.id.upload_button);

		if (savedInstanceState == null) {
			Bundle extras = getIntent().getExtras();
			interviewID = extras.getInt(ID_KEY);
		} else {
			interviewID = savedInstanceState.getInt(ID_KEY);
		}
		
		manager = LocalBroadcastManager.getInstance(this);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(ID_KEY, interviewID);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (receiver != null) {
			manager.registerReceiver(receiver, intentFilter);
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (receiver != null) {
			manager.unregisterReceiver(receiver);
		}
	}

	@Override
	protected void performDatabaseOperation() {
		interview = getService().getInterview(interviewID);
		listRecordingsButton.setEnabled(true);
		viewPhotosButton.setEnabled(true);
		uploadButton.setEnabled(true);
		errorTextView.setText("");
		if (interview != null) {
			storyTitleView.setText(interview.getStoryTitle());
			subjectNameView.setText(interview.getSubjectName().getReversedFullName());
			interviewerNameView.setText(interview.getInterviewerName().getReversedFullName());
			locationView.setText(interview.getLocationName());
			dateView.setText(DateFormat.getDateInstance().format(interview.getDate()));
			if (interview.getAudioFolderStatus()  == InterviewFileStatus.NOT_FOUND) {
				listRecordingsButton.setEnabled(false);
				uploadButton.setEnabled(false);
				errorTextView.setText(getString(R.string.audio_folder_missing));
			}
			if (interview.getPhotoFolderStatus() == InterviewFileStatus.NOT_FOUND) {
				viewPhotosButton.setEnabled(false);
				uploadButton.setEnabled(false);
				if (interview.getAudioFolderStatus()  == InterviewFileStatus.NOT_FOUND) {
					errorTextView.setText(getString(R.string.both_folders_missing));
				} else {
					errorTextView.setText(getString(R.string.photo_folder_missing));
				}

			}

		} else {
			fail(R.string.io_error);
		}
	}

	public void continueInterview(View view) {
		Intent intent = new Intent(view.getContext(), NewInterviewActivity.class);
		intent.putExtra(Util.ID_KEY, interviewID);
		startActivityForResult(intent, 0);
	}

	public void listAudio(View view) {
		Intent intent = new Intent(this, AudioListActivity.class);
		intent.putExtra(Util.ID_KEY, interviewID);
		startActivityForResult(intent, 0);
	}

	public void viewPhotos(View view) {
		Intent intent = new Intent(this, PhotoGalleryActivity.class);
		intent.putExtra(Util.ID_KEY, interviewID);
		startActivityForResult(intent, 0);
	}

	public void uploadInterview(View view) {
		if (Util.isLoggedIn(this)) {
			UploadDialogFragment fragment = new UploadDialogFragment();
			Bundle args = new Bundle();
			args.putInt(UploadDialogFragment.ID, interviewID);
			fragment.setArguments(args);
			fragment.show(getSupportFragmentManager(), UploadDialogFragment.FRAG_TAG);
		} else {
			receiver = new LoginBroadcastReceiver();
			manager.registerReceiver(receiver, intentFilter);

			// XXX This should probably be done with setArguments but I'm in a hurry
			LoginDialogFragment fragment = new LoginDialogFragment();
			fragment.setCallingActivity(this);
			fragment.show(getSupportFragmentManager(), LoginDialogFragment.FRAG_TAG);
		}
	}

	public void deleteInterview(View view) {
		Log.d(LOG_TAG, String.format("Attempting to delete item %d", interviewID));
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.delete_message));
		builder.setPositiveButton(R.string.delete_ok, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				AlertDialog.Builder builder = new AlertDialog.Builder(InterviewDetailActivity.this);
				builder.setMessage(R.string.delete_media_message);
				builder.setPositiveButton(R.string.delete_media_keep, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						getService().removeInterviewAndKeepMedia(interview);
						finish();
					}
				});
				builder.setNeutralButton(R.string.delete_ok, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							getService().removeInterview(interview);
							finish();
						} catch (IOException e) {
							Log.e(LOG_TAG, 
									String.format("Deleting interview %d threw an exception", 
											interviewID), 
											e);
							fail(R.string.io_error);
						}
					}
				});
				builder.setNegativeButton(R.string.cancel, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				});
				builder.create().show();
			}
		});
		builder.setNegativeButton(R.string.cancel, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Do nothing

			}
		});
		builder.create().show();
	}
	
	private class LoginBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String result = intent.getStringExtra(EthnographyUploadService.OUTPUT_RESULT);
			int id = Util.loginStringIDs.get(result);
			Toast toast = Toast.makeText(context, id, Toast.LENGTH_SHORT);
			toast.show();
			manager.unregisterReceiver(receiver);
			receiver = null;
		}

	}
}
